package com.cyzy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyzy.dto.CropDto;
import com.cyzy.dto.FieldDto;
import com.cyzy.dto.PlotOrdersPayDto;
import com.cyzy.dto.Result;
import com.cyzy.pojo.*;
import com.cyzy.service.CropService;
import com.cyzy.service.LandService;

import com.cyzy.service.PlotOrdersService;
import com.cyzy.service.ServiceTypeService;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.List;


@RestController
@RequestMapping("/land")
public class LandController {
    @Autowired
    private LandService landService;
    @Autowired
    private PlotOrdersService plotOrdersService;
    @Autowired
    private ServiceTypeService serviceTypeService;
    @Autowired
    private CropService cropService;
    //分页查询
    @GetMapping("/page")
    public Result getUserPage(
            @RequestParam(defaultValue = "1",name="current") Integer current,
            @RequestParam(defaultValue = "3",name="size")Integer size) {
        // 创建分页对象
        Page<Field> page = new Page<>(current, size);

        // 执行分页查询

        List<FieldDto> landList = landService.selectPage(page, null);
        PageInfo pageInfo = new PageInfo(landList);
        return Result.ok().data("landList",landList).data("total",pageInfo.getTotal());
    }
    @GetMapping("/getTypes")
    public Result getTypes() {
        List<ServiceType> list = serviceTypeService.getList();
        return Result.ok().data("types",list);
    }

    @GetMapping("/selectOrdersByUserId")
    public Result selectOrdersByUserId(@RequestParam("userId") Long userId,@RequestParam("plotOrderStatus")Long plotOrderStatus) {
        // 生成缓存键
        String cacheKey = "plot_orders:user:" + userId + ":status:" + plotOrderStatus;

        // 尝试从Redis获取缓存数据
        List<PlotOrders> cachedList = plotOrdersService.getOrdersFromCache(cacheKey);

        if (cachedList != null) {
            // 如果缓存中有数据，直接返回
            return Result.ok().data("orders", cachedList);
        } else {
            List<PlotOrders> list = plotOrdersService.selectOrdersByUserId(userId, plotOrderStatus);
            // 将结果存入Redis缓存
            plotOrdersService.cacheOrders(cacheKey, list);
            return Result.ok().data("orders",list);
        }

    }
    @GetMapping("/getCropByOrderNum")
    public Result getCropByOrderNum(@RequestParam("plotOrderNum") String plotOrderNum) {
        List<CropDto> list = plotOrdersService.selectCropByOrderNum(plotOrderNum);
        return Result.ok().data("crops",list);
    }
    @GetMapping("/getCropList")
    public Result getCropList(Crop crop) {
        List<Crop> list = cropService.getList(crop);
        return Result.ok().data("crops",list);
    }
    @GetMapping("/selectById1/{fieldId}")
    public Result selectById(
            @PathVariable("fieldId") Long fieldId) {
        FieldDto field = landService.selectById1(fieldId);
        return Result.ok().data("field",field);
    }
    @GetMapping("/selectByOwnerId/{fieldId}")
    public Result selectByOwnerId(
            @PathVariable("fieldId") Long fieldId) {
        List<Plot> plots = landService.selectByOwnerId(fieldId);
        return Result.ok().data("plots",plots).data("total",plots.size());
    }
    //小地块条件查询
    @GetMapping("/selectAll")
    public Result selectAll(Plot plot) {

    //        System.out.println(plot);
        List<Plot> plots = landService.selectAll(plot);
        return Result.ok().data("plots",plots).data("total",plots.size());
    }
    //订单号生成
    @GetMapping("/generateOrderNo")
    public Result generateOrderNo() {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String orderNo = "plot_order_" + timestamp;
        return Result.ok().data("plotOrderNum",orderNo);
    }
    @GetMapping("selectByOrderNum")
    public Result selectByOrderNum(@RequestParam("plotOrderNum") String plotOrderNum) {
        PlotOrders plotOrders = plotOrdersService.selectByOrderNum(plotOrderNum);
        return Result.ok().data("Order",plotOrders);
    }
    //订单生成
    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody PlotOrders plot) {
        try {
            PlotOrders plotOrders = plotOrdersService.selectByOrderNum(plot.getPlotOrderNum());
            System.out.println(plotOrders);
            if (plotOrders!=null){
                //订单号订单已存在,修改该订单信息并返回
                // 获取当前UTC时间
                Instant now = Instant.now();

                // 转换为本地时区计算（如需要）
                ZoneId zone = ZoneId.of("Asia/Shanghai");
                ZonedDateTime localNow = now.atZone(zone);


                // 计算开始时间（明天零点）
                ZonedDateTime startTime = localNow.plusDays(1)
                        .truncatedTo(ChronoUnit.DAYS);

                // 计算结束时间
                ZonedDateTime endTime = startTime.plusDays(plot.getLeastTime())
                        .with(LocalTime.MAX);

                // 转换回UTC时间戳
                Timestamp startTimestamp = Timestamp.from(startTime.toInstant());
                Timestamp endTimestamp = Timestamp.from(endTime.toInstant());
                plot.setLeastStartTime(startTimestamp);
                plot.setLeastEndTime(endTimestamp);
                // 3. 修改订单
                int success = plotOrdersService.updateOrder(plot);

                if (success>0) {
                    return Result.ok()
                            .message("修改成功")
                            .data("plotOrder",plotOrders);
                } else {
                    return Result.error().message("订单修改失败");
                }


            }
            else {
//                //不存在，执行插入新订单
//                // 1. 生成订单编号 plot_order + 时间戳
//                String timestamp = String.valueOf(System.currentTimeMillis());
//
//                plot.setPlotOrderNum("plot_order_" + timestamp);
//
//                // 获取当前UTC时间
//                Instant now = Instant.now();
//
//                // 转换为本地时区计算（如需要）
//                ZoneId zone = ZoneId.of("Asia/Shanghai");
//                ZonedDateTime localNow = now.atZone(zone);
//
//
//                // 计算开始时间（明天零点）
//                ZonedDateTime startTime = localNow.plusDays(1)
//                        .truncatedTo(ChronoUnit.DAYS);
//
//                // 计算结束时间
//                ZonedDateTime endTime = startTime.plusDays(plot.getLeastTime())
//                        .with(LocalTime.MAX);
//
//                // 转换回UTC时间戳
//                Timestamp startTimestamp = Timestamp.from(startTime.toInstant());
//                Timestamp endTimestamp = Timestamp.from(endTime.toInstant());
//                plot.setLeastStartTime(startTimestamp);
//                plot.setLeastEndTime(endTimestamp);
                // 3. 添加订单
                int success = plotOrdersService.addOrder(plot);

                if (success>0) {
                    return Result.ok()
                            .message("添加成功")
                            .data("PlotOrder", plot);
//                            .data("startTime", startTime)
//                            .data("endTime", endTime);
                } else {
                    return Result.error().message("订单添加失败");
                }
            }



        } catch (Exception e) {
            return Result.error().message("系统错误: " + e.getMessage());
        }
    }
    //订单支付
    @PostMapping("/payOrder")
    public Result payOrder(@RequestBody PlotOrdersPayDto plot) {
        //扣除用户余额（余额支付）
        Double orderAmount = plot.getOrderAmount();
        //修改订单状态为已支付
        plot.setPlotOrderStatus(1L);
        String msg = plotOrdersService.payOrder(plot);
        return Result.ok().message(msg);
    }


}
